package net.droiding.activity;

import net.droiding.app.Droiding;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ProviderActivity extends ListActivity {

	private ProgressDialog dlgProgress = null;
	private Droiding droiding = null;	
	private SimpleCursorAdapter adapter = null;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_2, null, new String[] {
						"name", "location" }, new int[] { android.R.id.text1,
						android.R.id.text2 });
		setListAdapter(adapter);

		final ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		droiding = Droiding.getInstance(this);
		populateList();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Cursor c = (Cursor)getListAdapter().getItem(position);
		String key = c.getString(c.getColumnIndex("pkey"));
		dlgProgress = ProgressDialog.show(ProviderActivity.this, "", 
                "Loading stations. Please wait...", true);
		droiding.changeProvider(key, hndChangeProviders);
	    
	}

    final Handler hndListProviders = new Handler() {
        public void handleMessage(Message msg) {
        	String result = msg.getData().getString("result");
        	if ("ok".equals(result)) {
        		dlgProgress.dismiss();
        		refreshProvidersList();
        		return;
        	}
        	if ("ko".equals(result)) {
        		dlgProgress.dismiss();
        		showErrorDialog(msg.getData().getString("error"));
        		return;
        	}
  
        }
    };
    final Handler hndChangeProviders = new Handler() {
        public void handleMessage(Message msg) {
        	String result = msg.getData().getString("result");
        	if ("ok".equals(result)) {
        		dlgProgress.dismiss();
        		setResult(RESULT_OK, new Intent());
        	    finish();	
        	}
        	if ("ko".equals(result)) {
        		dlgProgress.dismiss();
        		showErrorDialog(msg.getData().getString("error"));
        		return;
        	}
  
        }
    };

	
	private void populateList() {
		Cursor providersCursor = droiding.getDao().createProvidersCursor();
		if (providersCursor.getCount() == 0) {
			providersCursor.close();
			dlgProgress = ProgressDialog.show(ProviderActivity.this, "", 
                    "Loading providers. Please wait...", true);
			droiding.downloadProviders(hndListProviders);
			return;
		}		
		adapter.changeCursor(providersCursor);
		startManagingCursor(providersCursor);
	}
	private void refreshProvidersList() {
		Cursor providersCursor = null;
		try {
			providersCursor = droiding.getDao().createProvidersCursor();
		} catch (Exception e) {
			e.printStackTrace();
		}
		adapter.changeCursor(providersCursor);
		startManagingCursor(providersCursor);
		
	}
	private void showErrorDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(false).setPositiveButton("Retry",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						populateList();
					}
				}).setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();

	}
}
